const mongoose = require('mongoose')
const BillSource = mongoose.model('billSource')
const Bill = mongoose.model('bill')

const config = require('../config')
const { formatBody } = require('../tools')

module.exports = {
  // 发布广告
  async create (ctx) {
    let { uid, desc, link, images, totalNum, unitPrice } = ctx.request.body
    images = images || []
    if (!uid || !desc || !totalNum || !unitPrice) {
      return ctx.body = formatBody(0, '必传参数缺失')
    }
    let billSource = new BillSource({
      creator: uid, desc, link, images, totalNum, unitPrice
    })
    await billSource.save()
    return ctx.body = formatBody(1, '发布成功', billSource)
  },
  // 广告列表
  async billSourceList (ctx) {
    let { uid } = ctx.request.body
    if (!uid) {
      return ctx.body = formatBody(0, '请传入用户id')
    }
    let list = await BillSource.find({
      creator: uid
    }).populate({
      path: 'creator',
      select: 'avatar nickname _id'
    })
    return ctx.body = formatBody(1, 'ok', list)
  },
  // 领取广告
  async createBill (ctx) {
    let { uid, sourceId } = ctx.request.body
    if (!uid || !sourceId) {
      return ctx.body = formatBody(0, '必传参数缺失')
    }
    let hasBill = await Bill.findOne({
      source: sourceId
    })
    if (hasBill) {
      return ctx.body = formatBody(0, '你已经领取过该任务')
    }
    let billSource = await BillSource.findOne({
      _id: sourceId
    })
    let bill = new Bill({
      source: sourceId,
      executor: uid
    })
    billSource.receiveNum++
    billSource.bills.push(bill._id)
    await bill.save()
    await billSource.save()
    return ctx.body = formatBody(1, 'ok')
  }
}